/*
 * CharDataUnit.cpp
 *
 *  Created on: 21/04/2011
 *      Author: ehpalumbo
 */

#include <CharDataUnit.h>
#include <string.h>
#include <Logging.h>
#include <stdlib.h>

using namespace logging;

namespace chardataunits {

const unsigned int ASCII_TABLE_SIZE = 256;

CharDataUnit::CharDataUnit(const unsigned char data) {
	this->data = data;
}

CharDataUnit::CharDataUnit(const CharDataUnit& other) {
	this->data = other.asChar();
}

int CharDataUnit::asInt() const {
	return this->data;
}

void CharDataUnit::writeOn(ostream& os) {
	os << this->data;
}

unsigned char CharDataUnit::asChar() const {
	return this->data;
}

bool CharDataUnit::operator==(const DataUnit& other) {
	return (other.asInt() == this->asInt());
}

bool CharDataUnit::operator<(const DataUnit& other) {
	return (this->asInt() < other.asInt());
}


CharDataUnit::~CharDataUnit() {
}


CharDataUnitFactory::CharDataUnitFactory() {
	Logger& logger = LoggerFactory::getInstance().getLogger("DataUnit.CharDataUnitFactory");
	logger.log(logging::DEBUG, "Creating CharDataUnitFactory.");
	logger.log(logging::DEBUG, "Creating vector container for DataUnits.");
	this->dataUnits = new vector<DataUnit*>(ASCII_TABLE_SIZE);
	unsigned char data = 0;
	for (unsigned int i = 0; i< ASCII_TABLE_SIZE; i++) {
		this->dataUnits->at(i) = new CharDataUnit(data++);
	}
	logger.log(logging::DEBUG, "Created CharDataUnitFactory.");
}

vector<DataUnit*>& CharDataUnitFactory::getAll() {
	return *(this->dataUnits);
}

DataUnit* CharDataUnitFactory::createDataUnitFor(unsigned int value){
	if (value < ASCII_TABLE_SIZE){
		return new CharDataUnit(value);
	}else if (value == 257){
		return new Escape;
	}else if (value == 258){
		return new EndOfFileDataUnit;
	}
	return NULL;
}

CharDataUnitFactory::~CharDataUnitFactory() {
	for (unsigned int i = 0; i < ASCII_TABLE_SIZE; i++) {
		delete this->dataUnits->at(i);
	}
	delete this->dataUnits;
}

}
